/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
 * @author sherin
 */
public class Client extends MIDlet implements CommandListener {
    private Form form, messageForm, messageForm1;
    private Display display;
    private TextField txstatus, messageTxField, messageTxField1 ;
    private StreamConnection connection;
    private SocketConnection connection1;
    private OutputStream out = null;
    private InputStream in = null;
    private DataOutputStream outD = null;
    private DataInputStream inD = null;
    private List menu;
    private TextBox input;
    private Form loginDetails;
    private String currentMenu;
    private TextBox t;
    private TextField ip ;
    private TextField port;
    private String pwd = "D:";

    Ticker ticker = new Ticker("George, Karthik, Sherin");

    static final Command backCommand = new Command("Back", Command.BACK, 0);
    static final Command mainMenuCommand = new Command("Main", Command.SCREEN, 1);
    static final Command exitCommand = new Command("Exit", Command.STOP, 2);
    static final Command sendCommand = new Command("Send", Command.OK, 3);
    static final Command newMessage = new Command("newMessage", Command.OK, 4);
    static final Command deleteFile = new Command("Delete", Command.OK,5);
    static final Command copyFile = new Command("Copy", Command.OK, 6);
    static final Command cutFile = new Command("Cut", Command.OK, 6);
    static final Command pasteFile = new Command("Paste", Command.OK, 6);
    private String serverIP = null;
    private String serverDetails = null;
    private String serverPort = null;




    public void startApp() {
        display = Display.getDisplay(this);
        menu = new List("Main Menu", Choice.IMPLICIT);
        menu.append("Connect", null);
        menu.append("Settings", null);
        menu.addCommand(exitCommand);
        menu.setCommandListener(this);
        menu.setTicker(ticker);
        mainMenu();

    }
   void mainMenu() {
        display.setCurrent(menu);
        currentMenu = "Main Menu";
    }
    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
        try {
            out.close();
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        if(unconditional){
            notifyDestroyed();
        }
    }

    public void commandAction(Command c, Displayable d) {
         String label = c.getLabel();        // to capture the commands that are pressed
         System.out.println("Command is "+label);
         if( label.equals("Exit"))
            destroyApp(true);
        else if( label.equals("Back"))
            mainMenu();
        else if (label.equals("Connect")){
            setConnectionDetails(ip.getString(), port.getString());
           getServices();
        }
        else if(label.equals("View")){
            
        }
        else if (label.equals("Main"))
            mainMenu();
        else if( label.equals("Send")){
             sendMessageToServer( messageTxField.getString() );
        }
        else if( label.equals("newMessage")){
            // waiting for a new message from the client to be send to the server
            getMessageToSend();
        }
        else{                               //to capture the selections from list that is displayed in the window
              List down = (List)display.getCurrent();
              if( currentMenu.equals("Main Menu")){
                  switch(down.getSelectedIndex()){
                    case 0:
                        System.out.println("before getting login details ");
                        getLoginDetails();
                        break;
                  }
              }
              else if (currentMenu.equals("Connect Menu")){
                  switch(down.getSelectedIndex()){
                      case 0:
                          //create
                          break;
                      case 1:
                          
                          break;
                      case 2:
                          //View
                          break;
                      case 3:
                          //Delete
                          break;
                  }

              }
              else if (currentMenu.equals("Services Menu")){
                  switch(down.getSelectedIndex()){
                      case 0:
                          String homeDirectory = "fileBrowser\nls\n"+pwd;
                          sendMessageToServer(homeDirectory);
                          break;
                      
                  }

              }
              else if (currentMenu.equals("Browser Menu")){
                  switch(down.getSelectedIndex()){
                      case 0:
                          StringBuffer message = new StringBuffer();
                          message.append("fileBrowser\nls\n");
                          String dir = down.getString(down.getSelectedIndex());
                          System.out.println(dir+"   =========");
                          pwd = pwd+"/"+ dir;
                          message.append(pwd);
                          message.append("\n");
                          System.out.println(".............."+message);
                          sendMessageToServer(message.toString());
                          break;
                  }
              }
        }
    }

    private void connectMenu() {
        List  connectMenu = new List("Connect Menu", Choice.IMPLICIT);
        //TODO  it should read from the mobile memory
        connectMenu.append("Create", null);
        connectMenu.append("Start", null);
        connectMenu.append("View", null);
        connectMenu.append("Delete", null);
        connectMenu.addCommand(exitCommand);
        connectMenu.addCommand(mainMenuCommand);
        connectMenu.setCommandListener(this);
        currentMenu = "Connect Menu";
        display.setCurrent(connectMenu);
        

    }
    private void onnectServer() {
        try {
            connection = (StreamConnection)Connector.open(serverDetails);
            System.out.println("Connected to " + ip + ":" + port );
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void displayFileBrowser(String[] ResponseArray) {
        List  fileBrowseMenu = new List("File Browser", Choice.IMPLICIT);
        //TODO  it should read from the mobile memory
        //index 1 contains the pwd
        for( int i = 2; i< ResponseArray.length;i++)
        {
            fileBrowseMenu.append(ResponseArray[i], null);
        }

        fileBrowseMenu.addCommand(exitCommand);
        fileBrowseMenu.addCommand(mainMenuCommand);
        fileBrowseMenu.addCommand(deleteFile);
        fileBrowseMenu.setCommandListener(this);
        currentMenu = "Browser Menu";
        display.setCurrent(fileBrowseMenu);
    }

    private void displayMessage(String message) {
            messageForm1 = new Form("Message");
            messageTxField1 = new TextField("Message", message, 140, TextField.ANY);
            messageForm1.append(messageTxField1);
            messageForm1.addCommand(newMessage);
            messageForm1.setCommandListener(this);
            display.setCurrent(messageForm1);
            System.out.println("after receiving message from the server \n");
    }

    private void getLoginDetails() {
        System.out.println("getting login details");
        loginDetails = new Form("loginMenu");
        ip = new TextField("IP", "127.0.0.1", 50, 0);
        port = new TextField("Port", "8002", 50, 0 );
        Command connectCommand = new Command("Connect", Command.OK, 0);
        loginDetails.append(ip);
        loginDetails.append(port);        
        loginDetails.addCommand(mainMenuCommand);
        loginDetails.addCommand(connectCommand);
        loginDetails.setCommandListener(this);
        display.setCurrent(loginDetails);
    }
    
    private void getMessageToSend(){
        System.out.println("Getting a message from the mobile client");
        messageForm = new Form("Message");
        messageTxField = new TextField("Message", "", 140, TextField.ANY);
        messageForm.append(messageTxField);
        messageForm.addCommand(sendCommand);
        messageForm.setCommandListener(this);
        display.setCurrent(messageForm);
    }
    private void getServices(){
        sendMessageToServer("services");
    }

    private void listServices(String services[]) {
        List servicesMenu = new List("Services Menu", Choice.IMPLICIT);
        //TODO  it should read from the mobile memory
        servicesMenu.append(services[1], null);
        servicesMenu.addCommand(exitCommand);
        servicesMenu.addCommand(mainMenuCommand);
        servicesMenu.setCommandListener(this);
        currentMenu = "Services Menu";
        display.setCurrent(servicesMenu);


    }

    private String readMessageFromServer() throws IOException {
        String message = null;
        in = connection.openInputStream();
        StringBuffer request = new StringBuffer();
        int cmd = 0;
        System.out.println("before reading the message from the server");
        while(cmd!=-1){
            cmd = in.read();
            if(cmd ==-1 )
                break;
            request.append((char)cmd);
        }
        message = request.toString();
   
        return( message );
    }

    private void sendMessageToServer(String message){
        System.out.println("--sendMessageToServer");
        try {
            onnectServer();
            out = connection.openOutputStream();
            out.write(message.getBytes());
            out.flush();           
            out.close();
            message = readMessageFromServer();
            System.out.println("The reply from the server is :::: "  + message);
            processResponse(message);

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    private void processResponse(String Response){
        String[] ResponseArray = split(Response);
        System.out.println("the respons -------- " + Response);
        if( ResponseArray[0].equals("fileBrowser")){
            displayFileBrowser(ResponseArray);
        }
        else if(ResponseArray[0].equals("services")){
            listServices(ResponseArray);
        }

    }

    private void setConnectionDetails(String ip, String port) {
        serverIP = ip;
        serverPort = port;
        serverDetails = "socket://" + ip + ":" + port;
    }

    private String[] split(String original) {
        Vector nodes = new Vector();
        String separator = "\n";
 //       System.out.println("split start...................");
        // Parse nodes into vector
        int index = original.indexOf(separator);
        while(index>=0) {
            nodes.addElement( original.substring(0, index) );
            original = original.substring(index+separator.length());
            index = original.indexOf(separator);
        }
        // Get the last node
        nodes.addElement( original );
        // Create splitted string array
        String[] result = new String[ nodes.size() ];
        if( nodes.size()>0 ) {
            for(int loop=0; loop<nodes.size(); loop++)
            {
                result[loop] = (String)nodes.elementAt(loop);
                System.out.println(result[loop]);
            }
        }
        return result;
    }
}

